<template>
  <Dialog
    :title="title"
    :fullscreen="true"
    :model-value="visible"
    width="750px"
    maxHeight="800px"
    :before-close="closeForm"
  >
    <Form
      :schema="schema"
      :model="dept"
      @register="formRegister"
      label-width="200px"
      :isCol="false"
      :rules="rules"
    />
    <template #footer>
      <el-space>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-space>
    </template>
  </Dialog>
</template>

<script>
import { FileEnumDic } from '@/config/fileConfig'
import * as dirApi from '@/api/file/userFileDir'
import { Dialog } from '@/components/Dialog'
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { IsNull } from '@/utils'
const { formRegister, formMethods } = useForm()
export default {
  components: {
    Form,
    Dialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    const vaildateExtension = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (value.findIndex((c) => c == null || c == '' || !/^[.]\w+$/g.test(c)) !== -1) {
        callback(new Error('文件扩展名格式错误或为空!'))
      } else {
        callback()
      }
    }
    const vaildateUpPower = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (
        this.userDir.IsAccredit &&
        value.findIndex((c) => c == null || c == '' || !/^(\w|[.])+$/g.test(c)) !== -1
      ) {
        callback(new Error('上传权限码错误或为空!'))
      } else {
        callback()
      }
    }
    const vaildateReadPower = async (rule, value, callback) => {
      if (IsNull(value)) {
        callback()
      } else if (
        this.userDir.Power === 2 &&
        value.findIndex((c) => c == null || c == '' || !/^(\w|[.])+$/g.test(c)) !== -1
      ) {
        callback(new Error('上传权限码错误或为空!'))
      } else {
        callback()
      }
    }
    return {
      FileEnumDic,
      title: '新增用户文件目录',
      source: null,
      userDir: {},
      schema: [],
      rules: {
        DirKey: [
          {
            required: true,
            message: '目录Key不能为空！',
            trigger: 'blur'
          }
        ],
        AllowExtension: [
          {
            required: false,
            trigger: 'blur',
            validator: vaildateExtension
          }
        ],
        UpPower: [
          {
            required: false,
            trigger: 'blur',
            validator: vaildateUpPower
          }
        ],
        ReadPower: [
          {
            required: false,
            trigger: 'blur',
            validator: vaildateReadPower
          }
        ],
        DirName: [{ required: true, message: '目录名不能为空!', trigger: 'blur' }],
        DirStatus: [{ required: true, message: '目录状态不能为空!', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  methods: {
    formRegister,
    initSchema() {
      const list = [
        {
          field: 'basic',
          label: '基本信息',
          component: 'Divider'
        },
        {
          field: 'DirKey',
          label: '目录Key',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '目录Key'
          }
        },
        {
          field: 'DirName',
          label: '目录名',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '目录名'
          }
        },
        {
          field: 'DirStatus',
          label: '目录状态',
          component: 'EnumItem',
          componentProps: {
            placeholder: '目录状态',
            dicKey: FileEnumDic.dirStatus,
            sysHead: 'file'
          }
        },
        {
          field: 'UpShow',
          label: '上传说明',
          component: 'Input',
          componentProps: {
            maxlength: 100,
            placeholder: '上传说明'
          }
        },
        {
          field: 'upLimit',
          label: '上传限制',
          component: 'Divider'
        },
        {
          field: 'AllowUpFileSize',
          label: '最大文件大小(Byte字节)',
          component: 'InputNumber',
          componentProps: {
            placeholder: '最大文件大小(Byte字节)'
          }
        },
        {
          field: 'AllowExtension',
          label: '允许上传的文件扩展名',
          component: 'InputTag',
          componentProps: {
            placeholder: '允许上传的文件扩展名',
            clearable: true
          }
        },
        {
          field: 'imgSet',
          label: '图片上传限制',
          component: 'Divider'
        },
        {
          field: 'Ratio',
          label: '宽高比',
          component: 'NumRange',
          componentProps: {
            startPlaceholder: '宽',
            endPlaceholder: '高',
            clearable: true
          }
        },
        {
          field: 'WidthRange',
          label: '宽度范围(px)',
          component: 'NumRange',
          componentProps: {
            startPlaceholder: '最小宽度',
            endPlaceholder: '最大宽度',
            clearable: true,
            slots: {
              suffix: () => {
                return 'px'
              }
            }
          }
        },
        {
          field: 'HeightRange',
          label: '高度范围(px)',
          component: 'NumRange',
          componentProps: {
            startPlaceholder: '最小高度',
            endPlaceholder: '最大高度',
            clearable: true,
            slots: {
              suffix: () => {
                return 'px'
              }
            }
          }
        },
        {
          field: 'UpPowerInfo',
          label: '上传权限',
          component: 'Divider'
        },
        {
          field: 'IsAccredit',
          label: '是否需登陆',
          component: 'Switch',
          componentProps: {
            placeholder: '是否需登陆',
            on: {
              change: (val) => {
                this.userDir.IsAccredit = val
                this.initSchema()
              }
            }
          }
        }
      ]
      if (this.userDir.IsAccredit) {
        list.push({
          field: 'UpPower',
          label: '上传所需权限',
          component: 'InputTag',
          componentProps: {
            placeholder: '上传所需权限',
            clearable: true
          }
        })
        list.push({
          field: 'Power',
          label: '文件访问权限',
          component: 'EnumItem',
          componentProps: {
            dicKey: FileEnumDic.filePower,
            placeholder: '访问权限类型',
            sysHead: 'file',
            on: {
              change: (val) => {
                this.userDir.Power = val
                this.initSchema()
              }
            }
          }
        })
        if (this.userDir.Power === 2) {
          list.push({
            field: 'ReadPower',
            label: '读取所需权限',
            component: 'InputTag',
            componentProps: {
              placeholder: '读取所需权限',
              clearable: true
            }
          })
        }
      }
      this.schema = list
    },
    async save() {
      const data = await formMethods.validate()
      if (data == null) {
        return
      } else if (this.id) {
        this.set(data)
      } else {
        this.add(data)
      }
    },
    format(data) {
      const add = Object.assign({}, data)
      if (add.AllowUpFileSize === 0) {
        add.AllowUpFileSize = null
      }
      if (add.AllowExtension == null || add.AllowExtension.length == 0) {
        delete data.AllowExtension
      }
      const imgSet = {
        Ratio: add.Ratio && add.Ratio.length > 0 ? add.Ratio : null
      }
      delete add.Ratio
      if (data.WidthRange != null && data.WidthRange.length > 0) {
        imgSet.MinWidth = data.WidthRange[0]
        imgSet.MaxWidth = data.WidthRange[1]
      }
      delete add.WidthRange
      if (data.HeightRange != null && data.HeightRange.length > 0) {
        imgSet.MinHeight = data.HeightRange[0]
        imgSet.MaxHeight = data.HeightRange[1]
      }
      delete add.HeightRange
      add.UpImgSet = imgSet
      return add
    },
    async set(val) {
      const data = this.format(val)
      delete data.DirKey
      await dirApi.set(this.id, data)
      this.$message({
        message: '更新成功!',
        type: 'success'
      })
      this.$emit('update:visible', false)
      this.$emit('close', true)
    },
    async add(val) {
      const data = this.format(val)
      await dirApi.add(data)
      this.$message({
        message: '添加成功!',
        type: 'success'
      })
      this.$emit('update:visible', false)
      this.$emit('close', true)
    },
    async reset() {
      if (this.id == null) {
        this.title = '新增用户文件目录'
        this.source = null
      } else {
        const data = await dirApi.get(this.id)
        this.title = '编辑' + data.DirName + '用户文件目录'
        this.source = data
      }
      this.resetForm()
      this.initSchema()
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    },
    formatFileSize(size) {
      if (size == null || size === 0) {
        return '无限制'
      }
      size = parseInt(size)
      let t = 1024 * 1024 * 1024
      let num = Math.floor(size / t)
      let str = ''
      if (num !== 0) {
        str = num + 'GB '
        size = size % t
      }
      t = 1024 * 1024
      num = Math.floor(size / t)
      if (num !== 0) {
        str = str + num + 'MB '
        size = size % t
      }
      t = 1024
      num = Math.floor(size / t)
      if (num !== 0) {
        str = str + num + 'KB '
        size = size % t
      }
      if (size !== 0) {
        str = str + size + 'B'
      }
      return str
    },
    resetForm() {
      if (this.source == null) {
        this.userDir = {
          DirKey: null,
          DirName: null,
          DirStatus: 0,
          AllowUpFileSize: null,
          IsAccredit: false,
          Power: 0,
          UpShow: null,
          AllowExtension: [],
          Ratio: [],
          WidthRange: [],
          HeightRange: []
        }
      } else {
        const data = Object.assign({}, this.source)
        if (data.UpImgSet != null) {
          data.Ratio = data.UpImgSet.Ratio
          if (data.UpImgSet.MinWidth && data.UpImgSet.MaxWidth) {
            data.WidthRange = [data.UpImgSet.MinWidth, data.UpImgSet.MaxWidth]
          }
          if (data.UpImgSet.MinHeight && data.UpImgSet.MaxHeight) {
            data.HeightRange = [data.UpImgSet.MinHeight, data.UpImgSet.MaxHeight]
          }
        } else {
          data.Ratio = []
          data.WidthRange = []
          data.HeightRange = []
        }
        delete data.UpImgSet
        this.userDir = data
      }
      formMethods.setValues(this.userDir)
    }
  }
}
</script>
